/**
 * RegionAction.java
 * Created at 2017-2-8
 * Created by Administrator
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.rms.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.broadtext.common.bean.EntityPageBean;
import com.broadtext.common.exp.DaoException;
import com.broadtext.common.exp.ServiceException;
import com.broadtext.common.utils.RmsUtil;
import com.broadtext.rms.system.model.Region;
import com.broadtext.rms.system.service.IRegionService;
import com.broadtext.rms.system.service.ISysDictIndexService;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;

/**
 * <p>
 * ClassName: RegionAction
 * </p>
 * <p>
 * Description: 区域管理控制层
 * </p>
 * <p>
 * Author: Administrator
 * </p>
 * <p>
 * Date: 2017-2-8
 * </p>
 */
@Controller
@RequestMapping("/main/region")
public class RegionAction {
    /**
     * 日志信息
     */
    public static Logger logger = LoggerFactory.getLogger(RegionAction.class);

    /**
     * 区域服务类
     */
    @Autowired
    @Qualifier("regionService")
    private IRegionService regionService;
    
    /**
     * 字典service
     */
    @Autowired
    @Qualifier("sysDictIndexService")
    private ISysDictIndexService sysDictIndexService;
    
    /**
     * 
     * <p>Description: 区域分页查询</p>
     * @param request 请求对象
     * @param response 返回对象
     * @return 查询结果数据
     * @throws ServiceException 异常
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/findEntityPageByQuery.mvc")
    @ResponseBody
    public void findEntityPageByQuery(HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String jsonData;
        jsonData = request.getParameter("jsonData");
        JSONArray array;
        array = JSON.parseArray(jsonData);
        PageBounds pageBounds;
        pageBounds = new PageBounds();
        Map<String, Object> map;
        map = new HashMap<String, Object>();
        if (array != null) {
            Iterator it;
            it = array.iterator();
            while (it.hasNext()) {
                JSONObject obj;
                obj = (JSONObject) it.next();
                if (obj.get("value") != null && !"".equals(obj.get("value") + "")) {
                    map.put(obj.get("name") + "", obj.get("value"));
                }
            }
        }
        pageBounds.setLimit(Integer.parseInt(map.get("iDisplayLength").toString()));
        pageBounds.setPage(Integer.parseInt(map.get("iDisplayStart").toString()) / pageBounds.getLimit() + 1);
        EntityPageBean<Region> pageBean =  this.regionService.findEntityPageByQuery(map, pageBounds);
        Map<String, Object> dataMap=new HashMap<String, Object>();
        dataMap.put("recordsTotal", pageBean.getiTotalRecords());
        dataMap.put("recordsFiltered", pageBean.getiTotalRecords());
        dataMap.put("aaData", pageBean.getResults());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(JSON.toJSONString(dataMap));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    
    /**
     * <p>
     * Description: 获取区域树形结构
     * </p>
     * @param request 请求对象
     * @param response 返回对象
     * @return map数据
     */
    @RequestMapping(value = "/getRegionTree")
    @ResponseBody
    public Map<String, Object> getRegionTree(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        List<Region> list;
        list = new ArrayList<Region>();
        try {
            list = this.regionService.getRegionTree();
        } catch (DaoException e) {
            e.printStackTrace();
        }
        dataMap.put("aaData", list);
        return dataMap;
    }
    
    /**
     * <p>Description: 删除区域</p>
     * @param request 请求对象
     * @param pkId 主键
     * @param response 返回对象
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/delRegion.mvc")
    @ResponseBody
    public void delRegion(HttpServletRequest request, String pkId, HttpServletResponse response) {
        String[] regIdArray;
        regIdArray = pkId.split(",");
        try {
            this.regionService.delRegion(regIdArray,
                    String.valueOf(request.getSession().getAttribute("sys.userName")));
        } catch (DaoException e) {
            e.printStackTrace();
        }
        Map dataMap;
        dataMap = new HashMap();
        dataMap.put("msg", "success");
        RmsUtil.writeJsonStr(response, JSON.toJSONString(dataMap));
    }
    
    /**
     * <p>Description: 保存 或 更新区域</p>
     * @param request 请求
     * @param response 响应
     * @return String 操作结果
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/saveOrUpdateRegion.mvc")
    @ResponseBody
    public Map<String, Object> saveOrUpdateRegion(HttpServletRequest request, HttpServletResponse response) throws DaoException {
        Map<String, Object> dataMap;
        dataMap = new HashMap<String, Object>();
        String record;
        record = request.getParameter("record");
        String userName;
        userName = String.valueOf(request.getSession().getAttribute("sys.userName"));
        dataMap.put("msg", this.regionService.saveOrUpdateRegion(record, userName));
        return dataMap;
    }
    
    /**
     * <p>Description: 初始化编辑页面</p>
     * @param id 编辑对象id
     * @param request 请求对象
     * @param response 返回对象
     * @throws ServiceException 异常
     * @throws DaoException 异常
     */
    @RequestMapping(value = "/initEditRegionById")
    @ResponseBody
    public void initEditRegionById(String id, HttpServletRequest request, HttpServletResponse response) throws ServiceException, DaoException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("region", this.regionService.findEntityById(id));
        map.put("regionTypeDict", this.sysDictIndexService.getDictByParentKey("QYLXDM"));
        map.put("regTree", this.regionService.getRegionTree());
        RmsUtil.writeJsonStr(response, JSON.toJSONString(map));
    }
}
